package edu.fight.runner_once;

import edu.fight.utils.jwt.JwtUtils;
import edu.fight.utils.jwt.RsaFileInMemory;
import edu.fight.utils.jwt.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.File;
import java.nio.file.NoSuchFileException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 启动加载：
 * https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/htmlsingle/
 * 4.1.9. Using the ApplicationRunner or CommandLineRunner
 *
 */
@Component
@Slf4j
public class MyCommandLineRunner implements CommandLineRunner {

    /**
     * 启动加载至内存中 后续通过RsaFileInMemory 获取
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {

        log.info("启动执行一次");
        String protocol = MyCommandLineRunner.class.getResource("").getProtocol();
        File source = new ApplicationHome(MyCommandLineRunner.class).getDir();
        try {
            String absolutePath = source.getAbsolutePath();
            String privateKeyPath = JwtUtils.getPrivateKeyPath();
            String publicKeyPath = JwtUtils.getPublicKeyPath();
            // 避免与jar包内文件冲突，建议以绝对路径访问
            // 获取到当前项目所在路径，将文件放到项目路径下
            if (absolutePath.endsWith("/")) {
                publicKeyPath = absolutePath + publicKeyPath;
                privateKeyPath = absolutePath + privateKeyPath;
            } else if (absolutePath.endsWith("target/classes")){
                absolutePath = absolutePath.substring(0 , absolutePath.length() - "/target/classes".length());
            }else if (absolutePath.endsWith("/target")){
                absolutePath = absolutePath.substring(0 , absolutePath.length() - "/target".length());
            }else {
                publicKeyPath=absolutePath+"/"+publicKeyPath;
                privateKeyPath=absolutePath+"/"+privateKeyPath;
            }
            log.info("项目运行方式：[{}]，项目所在文件路径：[ {} ]", protocol, absolutePath);
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
            if (ObjectUtils.isEmpty(publicKey) || ObjectUtils.isEmpty(privateKey)) {
                log.error("未找到publicKey与privateKey，请检查文件在路径[{}]下是否存在！程序退出...", absolutePath);
                System.exit(255);
            }
            // 项目启动，将文件加载至内存
            RsaFileInMemory.setPublicKey(publicKey);
            RsaFileInMemory.setPrivateKey(privateKey);
        }catch (NoSuchFileException e){
            e.printStackTrace();
            log.error(e.getMessage(),e);
            System.exit(255);
        }

    }
}
